// 配置服务 - 从后端获取配置数据
class ConfigService {
  constructor() {
    this.configData = null
    this.loading = false
    this.error = null
  }

  // 获取配置数据
  async getConfig() {
    if (this.configData) {
      return this.configData
    }

    if (this.loading) {
      // 如果正在加载，等待完成
      return new Promise((resolve, reject) => {
        const checkLoading = () => {
          if (!this.loading) {
            if (this.error) {
              reject(this.error)
            } else {
              resolve(this.configData)
            }
          } else {
            setTimeout(checkLoading, 100)
          }
        }
        checkLoading()
      })
    }

    this.loading = true
    this.error = null

    try {
      console.log('正在从后端获取配置数据...')
      const response = await fetch('/api/config')
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const config = await response.json()
      console.log('配置数据获取成功:', config)
      
      // 转换后端数据格式为前端需要的格式
      this.configData = this.transformConfigData(config)
      return this.configData
    } catch (error) {
      console.error('获取配置失败:', error)
      this.error = error
      throw error
    } finally {
      this.loading = false
    }
  }

  // 转换后端配置数据格式
  transformConfigData(backendConfig) {
    // 转换年级数据为前端需要的格式
    const grades = this.transformGrades(backendConfig.grades || [])
    
    // 转换难度数据
    const difficulties = this.transformDifficulties(backendConfig.difficulties || [])
    
    return {
      grades,
      difficulties,
      subjects: backendConfig.subjects || [],
      knowledgePoints: backendConfig.knowledge_points || {},
      questionTypes: backendConfig.question_types || [],
      maxQuestions: backendConfig.max_questions || 50
    }
  }

  // 转换年级数据
  transformGrades(backendGrades) {
    const grades = [{ value: '', label: '请选择年级' }]
    
    // 分类年级
    const gradeCategories = {
      '小学': [],
      '初中': [],
      '高中': []
    }

    backendGrades.forEach(grade => {
      if (grade.includes('小学')) {
        const label = grade.replace('小学', '')
        gradeCategories['小学'].push({ value: grade, label })
      } else if (grade.includes('初') || grade.includes('初一') || grade.includes('初二') || grade.includes('初三')) {
        gradeCategories['初中'].push({ value: grade, label: grade })
      } else if (grade.includes('高')) {
        gradeCategories['高中'].push({ value: grade, label: grade })
      }
    })

    // 构建层级结构
    Object.entries(gradeCategories).forEach(([category, gradeList]) => {
      if (gradeList.length > 0) {
        grades.push({
          label: category,
          children: gradeList
        })
      }
    })

    return grades
  }

  // 转换难度数据
  transformDifficulties(backendDifficulties) {
    const difficultyEmojis = {
      '简单': '😊',
      '中等': '😐',
      '困难': '😤'
    }

    return backendDifficulties.map(difficulty => ({
      value: difficulty,
      label: `${difficultyEmojis[difficulty] || '😐'} ${difficulty}`
    }))
  }

  // 清除缓存（用于重新获取配置）
  clearCache() {
    this.configData = null
    this.error = null
  }
}

// 创建单例
const configService = new ConfigService()

export default configService